//
//  KLSGCityListViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/30.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGCityListViewController.h"
#import "KLSGCityListModel.h"
#import "KLSGCityRadioViewController.h"
#import "KLSGDataFail.h"

@interface KLSGCityListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *cityListArray;
// 声明KLSGCityListModel
@property (nonatomic, strong) KLSGCityListModel *cityListModel;

@property (nonatomic, strong) KLSGDataFail *dataFailView;

@end

@implementation KLSGCityListViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"省市台";
    
    [self addSubViews];
    [self setUpCityListData];
    
    
}

#pragma mark - 解析城市列表数据
- (void)setUpCityListData
{
    // 1.创建session对象  NSURLSession
    NSURLSession *session = [NSURLSession sharedSession];
    // 2.创建网址对象
    NSURL *url = [NSURL URLWithString:kCityListAPI];
    
    // 3.根据URL创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 4.建立会话 NSURLSessionDataTask
    // block中要使用self 需要用__block修饰一下
    __block KLSGCityListViewController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 5.解析
        if (data != nil) {
            
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
            
            NSArray *cityListArray = dic[@"result"];
            
            mySelf.cityListArray = [NSMutableArray array];
            for (NSDictionary *dic in cityListArray) {
                mySelf.cityListModel = [[KLSGCityListModel alloc] init];
                [mySelf.cityListModel setValuesForKeysWithDictionary:dic];
                [mySelf.cityListArray addObject:mySelf.cityListModel];
            }
            
            // 回到主线程刷新
            [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:self.tableView waitUntilDone:YES];
            
        } else {
            [mySelf performSelectorOnMainThread:@selector(failAction) withObject:nil waitUntilDone:YES];
        }
        
    }];
    
    // 6.启动解析
    [task resume];
    
}

#pragma mark - 重新加载数据
- (void)failAction
{
    self.dataFailView = [[KLSGDataFail alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 300)];
    self.tableView.tableFooterView = _dataFailView;
    [self.dataFailView netRequestFailWithBlock:^{
        [self setUpCityListData];
        [_dataFailView hidden];
    }];
}

#pragma mark - 刷新
- (void)reloadData:(UITableView *)tableView
{
    [tableView reloadData];
}

#pragma mark - 创建布局
- (void)addSubViews
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:(UITableViewStylePlain)];
    self.tableView.bounces = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    // 设置leftBarButton
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemReply) target:self action:@selector(leftReturn)];
    left.tintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
    self.navigationItem.leftBarButtonItem = left;
}

- (void)leftReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableView代理方法
#pragma mark - 分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.cityListArray.count;
}

#pragma mark - 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
        // cell 辅助按钮
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    // 显示数据
    if (self.cityListArray.count > 0) {
        // 通过下标获取model
        KLSGCityListModel *model = self.cityListArray[indexPath.row];
        cell.textLabel.text = model.provinceName;
    }
    
    return cell;
}

#pragma mark - 点击cell跳转到详情界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    KLSGCityRadioViewController *cityRadioVC = [[KLSGCityRadioViewController alloc] init];
    
    KLSGCityListModel *model = self.cityListArray[indexPath.row];
    cityRadioVC.provinceCodeID = model.provinceCode;
    cityRadioVC.cityTitle = model.provinceName;
    
    [self.navigationController pushViewController:cityRadioVC animated:YES];
}

#pragma mark - 延迟加载
- (NSMutableArray *)cityListArray
{
    if (!_cityListArray) {
        _cityListArray = [NSMutableArray array];
    }
    return _cityListArray;
}

- (KLSGDataFail *)dataFailView
{
    if (!_dataFailView) {
        _dataFailView = [[KLSGDataFail alloc] init];
    }
    return _dataFailView;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
